
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Thuy Duong
 */
public class SoundHelper implements PlayerListener {

    private String fileSource = "";
    private Player player = null;
    public String audioType = "audio/midi";
    InputStream inputStream;
    public SoundHelper(String fileSource) {
        try {
            this.fileSource = fileSource;
            inputStream = getClass().getResourceAsStream(fileSource);
            player = Manager.createPlayer(inputStream, audioType);
            player.addPlayerListener(this);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public SoundHelper(String fileSource, String audioType) {
        try {
            this.fileSource = fileSource;
            inputStream = getClass().getResourceAsStream(fileSource);
            this.audioType = audioType;
            player = Manager.createPlayer(inputStream, audioType);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public void setDuration(long duration) {
        try {
            player.setMediaTime(duration);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void setLoopCount(int loopCount) {
        try {
            player.setLoopCount(loopCount);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void setAudioType(String type){
        this.audioType = type;
    }

    public void playSound() {
        try {
            player.prefetch();
            player.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void stopSound() {
        try {
            player.stop();
            player.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void playerUpdate(Player player, String event, Object eventData) {
        try{
            if(event == PlayerListener.END_OF_MEDIA){
                player.stop();
                player.close();
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
